//
//  MyViewController.m
//  Zaker
//
//  Created by dllo on 16/3/16.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "MyViewController.h"
#import "WHUCalendarPopView.h"
#import "Scan_VC.h"
#import "ShouCangViewController.h"
#import "MapViewController.h"
#import <MessageUI/MessageUI.h>
#import "AboutViewController.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/TencentApiInterface.h>
@interface MyViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate,MFMailComposeViewControllerDelegate>

@property(nonatomic,retain)WHUCalendarPopView *pop;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UISwitch *mySwith;
@property(nonatomic, retain)NSMutableArray *arr;
@property (nonatomic, retain) UIView *naviBarView;
@property (nonatomic, retain) UIImageView *ima;
@property (nonatomic, retain) UICollectionView *collectionView;
@property(nonatomic,retain)TencentOAuth *tencentOAuth;
@property(nonatomic ,assign)BOOL  isLogined;
@property(nonatomic ,retain)UILabel *labelLoad;
@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self createNaviBar];
    [self createcollectionView];
    [self createSwitch];
    [self createTableView];
    self.arr  = [@[@"夜间模式", @"清除缓存", @"意见反馈", @"关于我们", @""] mutableCopy];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
}

- (void)createNaviBar
{
    self.naviBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 400 * HEIGHT)];
    [self.view addSubview: _naviBarView];
    _naviBarView.backgroundColor = [UIColor colorWithRed:0.890 green:0.161 blue:0.188 alpha:1.000];
    
    self.ima = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 120 * WIDTH, 120 * WIDTH)];
    _ima.center = CGPointMake(self.view.center.x, _naviBarView.center.y - 60);
    [self.view addSubview:_ima];
    _ima.image = [UIImage imageNamed:@"comment_profile_mars"];
    _ima.layer.cornerRadius = 120 * WIDTH / 2;
    _ima.clipsToBounds = YES;
    _ima.userInteractionEnabled = YES;
   self.labelLoad = [[UILabel alloc] initWithFrame:CGRectMake(0, _ima.frame.origin.y + _ima.frame.size.height + 10, SCREEN_WIDTH, 20 * HEIGHT)];
    [_naviBarView addSubview:self.labelLoad];
   
}
- (void)createcollectionView
{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.itemSize = CGSizeMake(SCREEN_WIDTH / 4, 100 * HEIGHT);
    flow.minimumInteritemSpacing = 0;
    flow.minimumLineSpacing = 0;
    flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,  HEIGHT*300, SCREEN_WIDTH, 100 * HEIGHT) collectionViewLayout:flow];
    [self.naviBarView addSubview:_collectionView];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.bounces = NO;
    [_collectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"cell2"];
}

- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 400 *HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - 370 * HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    
//    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 60, 0);
    self.tableView.bounces = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[MyTableViewCell class] forCellReuseIdentifier:@"cell"];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 6;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *arr = @[@"扫一扫", @"收藏", @"关注", @"日历", @"地图", @"天气"];
    NSArray *arrIma = @[[UIImage imageNamed:@"iconfont-iconfontscan"], [UIImage imageNamed:@"iconfont-shoucang"], [UIImage imageNamed:@"iconfont-guanzhu"], [UIImage imageNamed:@"iconfont-rili-2"], [UIImage imageNamed:@"iconfont-ditu"], [UIImage imageNamed:@"iconfont-tianqi"]];
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell2" forIndexPath:indexPath];
    cell.title.text = arr[indexPath.row];
    cell.ima.image = arrIma[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
   
    if (indexPath.item == 0) {
        Scan_VC *san =[[ Scan_VC alloc] init];
        [self presentViewController:san animated:YES completion:^{
            
        }];
        
    }
    
    if (indexPath.row == 2) {
        FollowViewController *follow = [[FollowViewController alloc] init];
        [self.navigationController pushViewController:follow animated:YES];
    }
    
    if (indexPath.item == 3) {
        self.pop = [[ WHUCalendarPopView alloc] init];
        _pop.onDateSelectBlk =^(NSDate *date)
        {
            NSDateFormatter *format  = [[NSDateFormatter alloc] init];
            [format setDateFormat:@"yyyy年MM月dd"];
            NSString *dateString = [format stringFromDate:date];
            
        };
        
        [_pop show];
    }
    
    if (indexPath.row == 5) {
        WeatherViewController *weather = [[WeatherViewController alloc] init];
        [self.navigationController pushViewController:weather animated:YES];
    }
    if (indexPath.item == 1) {
        ShouCangViewController *shoucang = [[ ShouCangViewController alloc] init];
        [self.navigationController  pushViewController:shoucang animated:YES];
    }

    if (indexPath.item == 4) {
     
        MapViewController *map = [[ MapViewController alloc] init];
        [self.navigationController pushViewController:map animated:YES];
    }

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _arr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.title.text = _arr[indexPath.row];
    
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = 0;
    if (indexPath.row == 0) {
        [cell addSubview:self.mySwith];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 3) {
        
        AboutViewController *about = [[ AboutViewController alloc] init];
        [self.navigationController pushViewController:about animated:YES];
    }
        if (indexPath.row == 2) {
            [AlertAndActionTool showActionSheetWithTitle:@"" Item1:@"打电话" AndItem2:@"发邮件" AndItem3:@"取消" AndViewController:self AndCallBack:^(int index) {
            
                if (index == 1) {
                    NSLog(@"打电话");
                    NSURL *url = [NSURL URLWithString:@"tel://18246174579"];
                    
                    [[UIApplication sharedApplication] openURL:url];

                }
                if (index == 2) {
                    NSLog(@"发邮件");
//                     当点击意见反馈时 调用激活邮件功能
                    if ([MFMailComposeViewController canSendMail]) { // 用户已设置邮件账户
                        [self sendEmailAction]; // 调用发送邮件的代码
                    }

                }
            }];
        }
    
  
    
    if (indexPath.row == 1) {
        float tmpSize = [[SDImageCache sharedImageCache] getSize];
        
        NSString *clearMessage = tmpSize >= 1024 * 1024 ? [NSString stringWithFormat:@"清理缓存(%.2fM)" , tmpSize / 1024 / 1024] : [NSString stringWithFormat:@"清理缓存(%.2fK)", tmpSize / 1024];
        
        [AlertAndActionTool showAlertWith:@"提示" AndContent:clearMessage AndViewController:self AndCallBack:^{
            [[SDImageCache sharedImageCache]clearDisk];
            
            //清除内存缓存
            [[[SDWebImageManager sharedManager] imageCache] clearMemory];
            
            //清除系统缓存
            [[NSURLCache sharedURLCache] removeAllCachedResponses];

        }];
        
    }
}

- (void)createSwitch {
    self.mySwith = [[UISwitch alloc] init];
    self.mySwith.frame = CGRectMake(300 * WIDTH, 1.5 * HEIGHT, 0, 0);
    [self.mySwith addTarget:self action:@selector(click:) forControlEvents:UIControlEventValueChanged];
    //从night中取出储存的字符串(yes,no)
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *passWord = [user objectForKey:@"night"];
    
    /*****************----------记住switch开关状态---------*****************/
    
    if ([passWord isEqualToString:@"yes"]) {
        [self.mySwith setOn:YES];
    }
    else {
        [self.mySwith setOn:NO];
    }
}

- (void)click:(UISwitch *)sender {
    
    //从night中取出字符串
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *passWord = [user objectForKey:@"night"];
    
    //当字符串是yes的时候发出no的消息
    if ([passWord isEqualToString:@"yes"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"change" object:@"no"];
    }
    else{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"change" object:@"yes"];
    }
    
}


- (void)sendEmailAction
{
    // 邮件服务器
    MFMailComposeViewController *mailCompose = [[MFMailComposeViewController alloc] init];
    // 设置邮件代理
    [mailCompose setMailComposeDelegate:self];
    // 设置邮件主题
    [mailCompose setSubject:@"我是邮件主题"];
    // 设置收件人
    [mailCompose setToRecipients:@[@"1369324218@qq.com"]];
    // 设置抄送人
    [mailCompose setCcRecipients:@[@"1369324218@qq.com"]];
    // 设置密抄送
    [mailCompose setBccRecipients:@[@"shana_happy@126.com"]];
    /**
     *  设置邮件的正文内容
     */
    NSString *emailContent = @"我是邮件内容";
    // 是否为HTML格式
    [mailCompose setMessageBody:emailContent isHTML:NO];
    // 如使用HTML格式，则为以下代码
    //	[mailCompose setMessageBody:@"<html><body><p>Hello</p><p>World！</p></body></html>" isHTML:YES];
    /**
     *  添加附件
     */
    UIImage *image = [UIImage imageNamed:@"image"];
    NSData *imageData = UIImagePNGRepresentation(image);
    [mailCompose addAttachmentData:imageData mimeType:@"" fileName:@"custom.png"];
    NSString *file = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"pdf"];
    NSData *pdf = [NSData dataWithContentsOfFile:file];
    [mailCompose addAttachmentData:pdf mimeType:@"" fileName:@"7天精通IOS233333"];
    // 弹出邮件发送视图
    [self presentViewController:mailCompose animated:YES completion:nil];
}
//MFMailComposeViewControllerDelegate的代理方法：

- (void)mailComposeController:(MFMailComposeViewController *)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled: // 用户取消编辑
            NSLog(@"Mail send canceled...");
            break;
        case MFMailComposeResultSaved: // 用户保存邮件
            NSLog(@"Mail saved...");
            break;
        case MFMailComposeResultSent: // 用户点击发送
            NSLog(@"Mail sent...");
            break;
        case MFMailComposeResultFailed: // 用户尝试保存或发送邮件失败
            NSLog(@"Mail send errored: %@...", [error localizedDescription]);
            break;
    }
    // 关闭邮件发送视图
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)logout
{
    
}
#pragma mark message
- (void)loginSuccessed
{
    if (NO == _isLogined)
    {
        _isLogined = YES;
    }
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"结果" message:@"登录成功" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
    [alertView show];
    
    NSArray *arrayCell = [[self tableView] visibleCells];
    for (id cell in arrayCell)
    {
        [[cell textLabel] setEnabled:_isLogined];
    }
}

- (void)loginFailed
{
   
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"结果" message:@"登录失败" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
    [alertView show];
}

- (void) loginCancelled
{
    //do nothing
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
